import 'dart:io';

import 'package:appupgrade/app_market.dart';
import 'package:appupgrade/appupgrade_platform_interface.dart';
import 'package:appupgrade/download_status.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:package_info_plus/package_info_plus.dart';

import 'package:flutter/services.dart';
import 'package:appupgrade/appupgrade.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body:  HomePage(),
      )
    );
  }
}


class HomePage extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return _HomepPage();
  }
}

class _HomepPage extends State<HomePage> {
  final _appupgradePlugin = Appupgrade();

  List<AppMarketInfo> _appMarketList = [];
  String _installMarkets = '';
  PackageInfo? _packageInfo;
  @override
  void initState() {
    _getInstallMarket();
    _getAppInfo();
    super.initState();
  }

  _checkAppUpgrade() {
    Appupgrade.appUpgrade(
      context,
      _checkAppInfo(),
      cancelText: '以后再说',
      okText: '马上升级',
      iosAppId: 'id88888888',
      appMarketInfo: AppMarket.huaWei,
      onCancel: () {
        print('onCancel');
      },
      onOk: () {
        print('onOk');
      },
      downloadProgress: (count, total) {
        print('count:$count,total:$total');
      },
      downloadStatusChange: (DownloadStatus status, {dynamic error}) {
        print('status:$status,error:$error');
      },
    );
  }

  Future<AppUpgradeInfo> _checkAppInfo() async {

    String url = "http://188.131.160.72:8088/storage/interactionclass.apk";

    //这里一般访问网络接口，将返回的数据解析成如下格式
    return Future.delayed(Duration(seconds: 1), () {
      return AppUpgradeInfo(
          title: '新版本V1.1.1',
          contents: [
            '1、支持立体声蓝牙耳机，同时改善配对性能',
            '2、提供屏幕虚拟键盘',
            '3、更简洁更流畅，使用起来更快',
            '4、修复一些软件在使用时自动退出bug',
            '5、新增加了分类查看功能'
          ],
          force: false,
          apkDownloadUrl: url
      );
    });
  }

  _getInstallMarket() async {
    if(Platform.isAndroid){
      List<String> marketList = await AppupgradePlatform.instance.getInstallMarket();
      marketList.forEach((f) {
        _installMarkets += '$f,';
      });
    }

  }

  _getAppInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() {
      _packageInfo = packageInfo;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
          child: Column(
            children: <Widget>[
              Text('packageName:${_packageInfo?.packageName}'),
              Text('versionName:${_packageInfo?.version}'),
              Text('versionCode:${_packageInfo?.buildNumber}'),
              Text('安装的应用商店:$_installMarkets'),

              Container(
                width: 200,
                height: 40,
                color: Colors.orange,
                child: InkWell(
                  child: Text("检测更新"),
                  onTap: (){
                    _checkAppUpgrade();
                  },
                ),
              )
            ],
          )
      ),
    );
  }
}
